package com.qyhl.school.school.center.vlog;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolThemeBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class SchoolCenterVlogFragment extends BaseFragment implements SchoolCenterVlogContract.SchoolCenterVlogView {
    @BindView(R2.id.vlog_recycler)
    RecyclerView vlogRecycler;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;


    private SchoolCenterVlogPresenter mPresenter;

    private HeaderAndFooterWrapper<SchoolVlogBean> mHeaderAndFooterWrapper;

    private String username;

    private String nickName, headIcon;

    private CommonAdapter<SchoolThemeBean> commonAdapter;
    private List<SchoolThemeBean> themeList = new ArrayList<>();

    private CommonAdapter<SchoolVlogBean> vlogCommonAdapter;
    private List<SchoolVlogBean> vlogList = new ArrayList<>();

    private int tagId = 0;

    private int lastId = 0;

    public static SchoolCenterVlogFragment newInstance() {
        SchoolCenterVlogFragment fragment = new SchoolCenterVlogFragment();
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_center_vlog, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        BusFactory.getBus().register(this);

        mPresenter = new SchoolCenterVlogPresenter(this);

        username = CommonUtils.getInstance().getUserName();
        headIcon = CommonUtils.getInstance().getUserLogo();
        nickName = CommonUtils.getInstance().getNickName();

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        //初始化头部
        View headView = LayoutInflater.from(getContext()).inflate(R.layout.layout_school_center_vlog_header, null);
        RecyclerView themeRecycler = headView.findViewById(R.id.theme_recycler);

        themeRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        themeRecycler.setAdapter(commonAdapter = new CommonAdapter<SchoolThemeBean>(getContext(), R.layout.item_school_center_vlog_theme, themeList) {
            @Override
            protected void convert(ViewHolder viewHolder, SchoolThemeBean schoolThemeBean, int i) {
                viewHolder.setText(R.id.title, "#" + schoolThemeBean.getName() + "#");
                if (schoolThemeBean.isSelected()) {
                    viewHolder.setTextColorRes(R.id.title, R.color.white);
                    viewHolder.setBackgroundRes(R.id.title, R.drawable.school_reporter_home_act_sign);
                } else {
                    viewHolder.setTextColorRes(R.id.title, R.color.global_black_lv1);
                    viewHolder.setBackgroundRes(R.id.title, R.color.white);
                }
            }
        });

        vlogRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
        vlogCommonAdapter = new CommonAdapter<SchoolVlogBean>(getContext(), R.layout.item_school_vlog_home, vlogList) {
            @Override
            protected void convert(ViewHolder holder, SchoolVlogBean schoolVlogBean, int i) {
                holder.setText(R.id.nickName, nickName);
                if (schoolVlogBean.getTag() != null) {
                    holder.setText(R.id.tagName, "#" + schoolVlogBean.getTag().getName() + "#");
                }
                holder.setText(R.id.description, schoolVlogBean.getInfo());

                RoundedImageView cover = holder.getView(R.id.cover);
                RoundedImageView headCover = holder.getView(R.id.head_cover);

                Glide.with(SchoolCenterVlogFragment.this)
                        .load(schoolVlogBean.getVideoUrl())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                Glide.with(SchoolCenterVlogFragment.this)
                        .load(headIcon)
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headCover);
            }
        };

        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper<SchoolVlogBean>(vlogCommonAdapter);
        mHeaderAndFooterWrapper.addHeaderView(headView);
        vlogRecycler.setAdapter(mHeaderAndFooterWrapper);

        if (StringUtils.isNotEmpty(username)) {
            mPresenter.getThemeList(username);
        } else {
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText("请先登录");
        }

    }

    @Override
    protected void setListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                for (int i = 0; i < themeList.size(); i++) {
                    if (i == position) {
                        if (themeList.get(i).isSelected()) {
                            themeList.get(i).setSelected(false);
                            tagId = 0;
                            lastId = 0;
                        } else {
                            themeList.get(i).setSelected(true);
                            tagId = themeList.get(i).getId();
                            lastId = 0;
                        }
                    } else {
                        themeList.get(i).setSelected(false);
                    }
                }
                commonAdapter.notifyDataSetChanged();
                mPresenter.getList(username, tagId, lastId);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        vlogCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                int position = 0;
                if (vlogRecycler.getAdapter().getItemCount() == vlogList.size()) {
                    position = i;
                } else {
                    if (i >= 1) {
                        position = i - 1;
                    }
                }
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) vlogList);
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_VLOG_PLAY)
                        .withInt("position",position)
                        .withInt("type",1)
                        .withBundle("list",bundle)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getThemeList(username);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(username, tagId, lastId);
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                if (StringUtils.isEmpty(username)) {
                    loadMask.setStatus(LoadingLayout.Error);
                    loadMask.setErrorText("请先登录");
                } else {
                    loadMask.setReloadButtonText("加载中...");
                    mPresenter.getThemeList(username);
                }

            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void setThemeList(List<SchoolThemeBean> beanList) {
        themeList.clear();

        for (int i = 0; i < beanList.size(); i++) {
            SchoolThemeBean bean = beanList.get(i);
            if (i == 0) {
                tagId = bean.getId();
                bean.setSelected(true);
            } else {
                bean.setSelected(false);
            }
            themeList.add(bean);
        }
        commonAdapter.notifyDataSetChanged();

        mPresenter.getList(username, tagId, lastId);
    }

    @Override
    public void setThemeError(String msg) {
        showToast(msg, 4);
        tagId = 0;
        lastId = 0;
        mPresenter.getList(username, tagId, lastId);
    }

    @Override
    public void setList(List<SchoolVlogBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            vlogList.clear();
        }
        lastId = beanList.get(beanList.size() - 1).getId();
        vlogList.addAll(beanList);
        mHeaderAndFooterWrapper.notifyDataSetChanged();

    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                username = CommonUtils.getInstance().getUserName();
                headIcon = CommonUtils.getInstance().getUserLogo();
                nickName = CommonUtils.getInstance().getNickName();
                mPresenter.getThemeList(username);
            } else {
                loadMask.setStatus(LoadingLayout.Error);
                loadMask.setErrorText("请先登录");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }

}
